import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import { defineConfig, loadEnv, UserConfig, UserConfigExport } from "vite";
import { createHtmlPlugin } from "vite-plugin-html";
import tsconfigPaths from "vite-tsconfig-paths";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import Icons from "unplugin-icons/vite";

export default (config: UserConfig): UserConfigExport => {
  const mode = config.mode as string;
  return defineConfig({
    base: "./",
    plugins: [
      vue(),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            apiURL: loadEnv(mode, process.cwd()).VITE_WEB_API,
            title: ""
          },
          tags: [
            {
              injectTo: "body-prepend",
              tag: "div",
              attrs: {
                id: "tag"
              }
            }
          ]
        }
      }),
      Icons({
        compiler: "vue3",
        autoInstall: true,
        scale: 1
      }),
      tsconfigPaths(),
      createSvgIconsPlugin({
        iconDirs: [resolve(__dirname, "src/assets/icons/svg")],
        symbolId: "icon-[dir]-[name]"
      })
    ],
    build: {
      chunkSizeWarningLimit: 1024,
      commonjsOptions: {
        include: /node_modules|lib/
      },
      rollupOptions: {
        output: {
          manualChunks: {
            quill: ["quill"],
            lodash: ["lodash-es"],
            vlib: ["vue", "vue-router", "pinia"],
            elementPlus: ["element-plus", "@element-plus/icons-vue"],
            echarts: ["echarts", "vue-echarts"],
            utils: ["axios", "crypto-js", "jsencrypt"]
          }
        }
      }
    },
    resolve: {
      alias: {
        // 配置别名
        "@": resolve(__dirname, "./src")
      }
    },
    server: {
      // open: false, // 自动启动浏览器
      host: true, // localhost
      port: 5173, // 端口号
      // hmr: { overlay: false },
      proxy: {
        // web端几口代理
        "/installer": { 
          target: "http://120.77.15.185:8089",
          // target: "http://172.16.20.61:8080",
          // target: "http://172.16.20.10:8080",
          changeOrigin: true,
          secure: false // 仅限开发环境！
        },
        // 专用于 tdengine 网关：仅 /v2/as/tdengine/** 转发到 uat 域名
        "/v2/as/tdengine": {
          target: "https://uat.zendure.tech",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/v2/, ""),
        },
        // // 新增：app 端接口代理
        "/v2": {
          // 如需切换环境，这里改成对应后端地址
          target: "http://120.77.15.185:8092",
          // target: "http://172.16.20.137:8080",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/v2/, ''),
        },
      }
    },
  });
};
